import 'package:canteen/dio/user_dio.dart';
import 'package:canteen/method/showDialog.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:canteen/edit_c_v.dart';
import '../component/line_button.dart';
import '../dio/configure_dio.dart';
import '../menu_c_v.dart';
import 'choose_page.dart';
import 'edit_line_page.dart';
import 'package:canteen/userDetail.dart';

class StaffDetailPage extends StatefulWidget {
  static String id = 'staff_detail_page';

  const StaffDetailPage({super.key});

  @override
  State<StaffDetailPage> createState() => _StaffDetailPageState();
}

class _StaffDetailPageState extends State<StaffDetailPage> {
  int id = 0;
  Map<String, String> convertRole = {
    'NORMAL': '员工',
    'ADMIN': '管理员',
    'GUEST': '访客',
  };

  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
    final Map<String, dynamic>? args =
        ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
    name = args?['username'];
    staffType = convertRole[args?['staffType']]??'超级管理员';
    id = args?['id'];
    password = args?['password'];
    department =
        allStaffs.firstWhere((element) => element.username == name).department;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffafafa),
      appBar: AppBar(
        backgroundColor: Color(0xffffffff).withOpacity(0.89),
        elevation: 0,
        centerTitle: true,
        title: Text(
          '员工信息',
          style: TextStyle(color: Colors.black, fontSize: 16),
        ),
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_rounded,
            color: Colors.black,
          ),
        ),
        actions: [
          GestureDetector(
            onTap: () {
              uploadData();
            },
            child: Icon(
              Icons.save_outlined,
              color: Colors.black,
            ),
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Container(
        margin: EdgeInsets.symmetric(horizontal: 30),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15, vertical: 8),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(25),
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    offset: Offset(0, 1),
                    blurRadius: 2,
                    color: Colors.black.withOpacity(0.25),
                  )
                ],
              ),
              child: Column(
                children: [
                  Builder(
                    builder: (context) => LineButton(
                      title: '用户名',
                      content: Text(
                        name,
                        style: TextStyle(color: Colors.black, fontSize: 16),
                        softWrap: true,
                      ),
                      onPressed: () {
                        if(staffType=='超级管理员'){
                          return;
                        }
                        Navigator.pushNamed(context, EditLinePage.id,
                            arguments: {'title': '用户名'}).then((value) {
                          setState(() {});
                        });
                      },
                    ),
                  ),
                  Builder(
                    builder: (context) => LineButton(
                      title: '密码',
                      content: Text(
                        password,
                        style: TextStyle(color: Colors.black, fontSize: 16),
                        softWrap: true,
                      ),
                      onPressed: () {
                        if(staffType=='超级管理员'){
                          return;
                        }
                        Navigator.pushNamed(context, EditLinePage.id,
                            arguments: {'title': '密码'}).then((value) {
                          setState(() {});
                        });
                      },
                    ),
                  ),
                  LineButton(
                    isSelect: true,
                    title: '身份',
                    content: Text(
                      staffType,
                      style: TextStyle(color: Color(0xff2b3db5), fontSize: 16),
                      softWrap: true,
                    ),
                    onPressed: () {
                      if(staffType=='超级管理员'){
                        return;
                      }
                      options = convertRole.values.toList();
                      showModalBottomSheet(
                          context: context,
                          builder: (context) => ChoosePage()).then((_) {
                        setState(() {});
                      });
                    },
                  ),
                  LineButton(
                    isSelect: true,
                    title: '部门',
                    content: Text(
                      department,
                      style: TextStyle(color: Color(0xff2b3db5), fontSize: 16),
                      softWrap: true,
                    ),
                    onPressed: () {
                      if(staffType=='超级管理员'){
                        return;
                      }
                      if (departments.isNotEmpty) {
                        options = departments;
                        showModalBottomSheet(
                            context: context,
                            builder: (context) => ChoosePage()).then((_) {
                          setState(() {});
                        });
                      }
                    },
                  ),
                ],
              ),
            ),
            staffType=='超级管理员'
                ? SizedBox()
                : FloatingActionButton(
                    backgroundColor: Color(0xffc80815),
                    onPressed: () {
                      deleteStaff();
                    },
                    child: Icon(
                      Icons.delete_outline_rounded,
                    ),
                  ),
          ],
        ),
      ),
    );
  }

  Future<void> uploadData() async {
    try {
      Response response = await updateUser(user: {
        'id': id,
        'username': name,
        'password': password,
        'type': convertRole.entries
            .firstWhere((element) => element.value == staffType)
            .key,
        'department': department,
      }, dio: dio);
      allStaffs.firstWhere((element) => element.id == id)
        ..password = password
        ..username = name
        ..type = convertRole.entries
            .firstWhere((element) => element.value == staffType)
            .key
        ..department = department;
      ShowDialog.showCorrectAndDetail(context, '上传成功');
    } on Exception catch (e) {
      ShowDialog.showErrorAndDetail(context, '上传失败');
    }
  }

  Future<void> deleteStaff() async {
    try {
      Response response = await deleteUserById(user: {'id': id}, dio: dio);
      allStaffs.removeWhere((element) => element.id == id);
      ShowDialog.showCorrectAndDetail(context, '删除成功');
    } on Exception catch (e) {
      // TODO
      ShowDialog.showErrorAndDetail(context, '删除失败');
    }
  }
}
